package com.shouhuobao.take.recharge;

import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.CheckBox;
import android.widget.TextView;
import android.widget.Toast;

import com.alipay.sdk.app.PayTask;
import com.iseastar.BaseActivity2;
import com.iseastar.alipay.PayResult;
import com.iseastar.guojiang.app.AppCache;
import com.iseastar.guojiang.app.Intents;
import com.iseastar.guojiang.consts.MsgID;
import com.iseastar.guojiang.logic.AppHttp;
import com.iseastar.guojiang.logic.JSON;
import com.iseastar.guojiang.model.ReqResult;
import com.shb.model.OrderPayBean;
import com.shb.model.WxPayModel;
import com.shouhuobao.station.R;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import droid.frame.utils.android.MathUtils;

/**
 * 短信充值
 *
 * @author coffee<br>
 *         2017年6月9日下午3:01:58
 */
public class SmsPayActivity extends BaseActivity2 implements OnClickListener {

    private String orderId;
    private CheckBox mAliPay, mWxPay;

    @Override
    protected void findViewById() {
        setContentView(R.layout.sms_pay);
        super.findViewById();
        getAppTitle().setCommonTitle("收银台");
        //
        String number = getIntent().getStringExtra("number");
        String remain = getIntent().getStringExtra("remain");
        String price = getIntent().getStringExtra("price");
        orderId = getIntent().getStringExtra("orderId");

        TextView mSmsNumber = (TextView) findViewById(R.id.sms_number);
        TextView mSmsPrice = (TextView) findViewById(R.id.sms_payprice);
        TextView mSmsRemain = (TextView) findViewById(R.id.sms_remain);
        mSmsRemain.setText(remain);
        mSmsNumber.setText(number);
        mSmsPrice.setText(MathUtils.mul(number, price) + "");
        //
        mAliPay = (CheckBox) findViewById(R.id.sms_pay_ali);
        mAliPay.setChecked(true);
        mWxPay = (CheckBox) findViewById(R.id.sms_pay_wx);
        findViewById(R.id.sms_pay_ali_layout).setOnClickListener(this);
        findViewById(R.id.sms_pay_wx_layout).setOnClickListener(this);
        findViewById(R.id.submit).setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.sms_pay_ali_layout:
                mAliPay.setChecked(true);
                mWxPay.setChecked(false);
                break;
            case R.id.sms_pay_wx_layout:
                mAliPay.setChecked(false);
                mWxPay.setChecked(true);
                break;
            case R.id.submit:
                AppCache.setOrderId(orderId);
                AppHttp.getInstance().takeSmsOrderPay(orderId, mWxPay.isChecked() ? 0 : 1);
                break;
        }
    }

    @Override
    public boolean handleMessage(Message msg) {
        switch (msg.what) {
            case MsgID.take_sms_order_pay:
                ReqResult<?> result = null;
                if (mWxPay.isChecked()) {
                    result = JSON.parser(msg.obj, WxPayModel.class);
                } else {
                    result = JSON.parser(msg.obj.toString());
                }
                if (checkLoginStatus(result)) {
                    if (mWxPay.isChecked()) {
                        if (result.isSuccess()) {
                            WxPayModel wxModel = (WxPayModel) result.getResult();
                            if (wxModel == null) {
                                return true;
                            }
                            com.shb.model.OrderPayBean pay = new com.shb.model.OrderPayBean(wxModel);
                            handleWxpay(pay);
                        }
                    } else {
                        alipay(result.getResult().toString());
                    }
                } else {
                    showToast(result.getMessage());
                }
                return true;
            default:
                return super.handleMessage(msg);
        }
    }

    ///

    /**
     * 处理跳转到微信支付
     *
     * @param pay
     */
    private void handleWxpay(OrderPayBean pay) {
        if (pay == null) {
            Toast.makeText(this, "订单数据异常", Toast.LENGTH_SHORT).show();
        } else {
            sendPayReq(pay);
        }
    }

    private void sendPayReq(OrderPayBean pay) {
        IWXAPI msgApi = WXAPIFactory.createWXAPI(this, null);
        msgApi.registerApp(pay.getAppid());
        if (msgApi.isWXAppInstalled() == false) {
            showToast("未安装微信");
            return;
        }
        //
        PayReq req = new PayReq();
        req.appId = pay.getAppid();
        req.partnerId = pay.getPartnerid();
        req.prepayId = pay.getPrepayid();
        req.packageValue = pay.getPackageValue();
        req.nonceStr = pay.getNoncestr();
        req.timeStamp = pay.getTimestamp();
        req.sign = pay.getSign();
        //
        msgApi.sendReq(req);
    }

    private final int SDK_PAY_FLAG = 1;
    private final int SDK_CHECK_FLAG = 2;

    private Handler mPayHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG: {
                    PayResult payResult = new PayResult((String) msg.obj);
                    // 支付宝返回此次支付结果及加签，建议对支付宝签名信息拿签约时支付宝提供的公钥做验签
                    // String resultInfo = payResult.getResult();
                    String resultStatus = payResult.getResultStatus();
                    // 判断resultStatus 为“9000”则代表支付成功，具体状态码代表含义可参考接口文档
                    if (TextUtils.equals(resultStatus, "9000")) {
                        Toast.makeText(getContext(), "支付成功", Toast.LENGTH_SHORT).show();
                        AppHttp.getInstance().takePayReturn(orderId, 2);
                        finish();
                        Intents.startTakeMainActivity(getContext());
                    } else {
                        // 判断resultStatus 为非“9000”则代表可能支付失败
                        // “8000”代表支付结果因为支付渠道原因或者系统原因还在等待支付结果确认，最终交易是否成功以服务端异步通知为准（小概率状态）
                        if (TextUtils.equals(resultStatus, "8000")) {
                            Toast.makeText(getContext(), "支付结果确认中", Toast.LENGTH_SHORT).show();
                        }
                        // 6001代表支付取消
                        if (TextUtils.equals(resultStatus, "6001")) {
                            showToast("支付取消");
                        } else {
                            // 其他值就可以判断为支付失败，包括用户主动取消支付，或者系统返回的错误
                            Toast.makeText(getContext(), "支付失败，请重试！", Toast.LENGTH_SHORT).show();
                        }
                    }
                    break;
                }
                case SDK_CHECK_FLAG: {
                    Toast.makeText(getContext(), "检查结果为：" + msg.obj, Toast.LENGTH_SHORT).show();
                    break;
                }
                default:
                    break;
            }
        }

        ;
    };

    /**
     * call alipay sdk pay. 调用SDK支付
     */
    public void alipay(final String payInfo) {
        Runnable payRunnable = new Runnable() {
            @Override
            public void run() {
                // 构造PayTask 对象
                PayTask alipay = new PayTask(getContext());
                // 调用支付接口，获取支付结果
                String result = alipay.pay(payInfo, true);

                Message msg = new Message();
                msg.what = SDK_PAY_FLAG;
                msg.obj = result;
                mPayHandler.sendMessage(msg);
            }
        };

        // 必须异步调用
        Thread payThread = new Thread(payRunnable);
        payThread.start();
    }

}
